<?php

namespace XWAM\TagLib;

/**
 * TagBase 标签类基类
 *
 * @since VER:1.0; DATE:2016-6-16; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class TagBase extends \Think\Template\TagLib {

    /**
     * 解析SQL属性
     * @param type $attr
     * @return type
     * @since 1.0 2016-6-16 SoChishun Added.
     */
    protected function parseSQLOption($attr) {
        $asql_attr = array('where', 'field', 'limit', 'order', 'table');
        $options = array();
        foreach ($asql_attr as $key) {
            if (!empty($attr[$key])) {
                $options[$key] = $attr[$key];
            }
        }

        if (!empty($options['where'])) {
            // where是模板变量
            if ('$' == $options['where'][0]) {
                $options['where'] = $this->tpl->get(substr($options['where'], 1));
                return $options;
            }
            // where是表达式(标签不支持<>等html标签,只能用neq,gt,lt代替表达式)
            $alias = array('neq' => '<>', 'gt' => '>', 'lt' => '<', 'egt' => '>=', 'elt' => '<=');
            foreach ($alias as $key => $value) {
                $options['where'] = str_replace(" $key ", " $value ", $options['where']);
            }
            // where内容是json_encode()处理过的字符串,如where='{"pid":20}'
            if ('{' == $options['where'][0]) {
                $options['where'] = json_decode($options['where'], true);
            }
        }
        return $options;
    }

    /**
     * 解析Id表达式
     * @param type $idval
     * @since 1.0 2015-11-12 SoChishun Added.
     * @example id="$Think.Get.id??3"
     */
    protected function parseIdExp($idval) {
        $idval = $attr['id'];
        if (strpos($idval, '??')) {
            $aval = explode('??', $idval);
            $idval = $aval[0];
            if (false !== strpos($idval, '$Think')) {
                $idval = $this->parseThinkVar($idval);
            }
            $idval = '(isset(' . $idval . ') ? ' . $idval . ' : ' . $aval[1] . ')';
        } else {
            if (false !== strpos($idval, '$Think')) {
                $idval = $this->parseThinkVar($idval);
            }
        }
        return $idval;
    }

}
